/**
 * create by young (young2f@outlook.com) on 2020/9/16
 * 选择包装
 */


'use strict';
import React from 'react';
import {Button, DatePicker, Form, Input, InputNumber, notification, Select, Table} from 'antd';

import FormBase from '../../../components/Base/FormBase';
import {connect} from "dva";
import moment from 'moment';
import 'moment/locale/zh-cn';
import ViewTitle from "../../../components/ViewTitle";
import {FormField, FormLayout, ModalFooter} from "antd-extra";
import notify from "../../../components/NotificationExtra";
import styles from "../../index.less";
import AutoCompletePlus from "../../../common/AutoCompletePlus";
import MaterialElement from "../../finance/modal/MaterialElement";
import ElementItem from "../../../components/ElementItem";

const {Option} = Select;
moment.locale('zh-cn');
const table = 'ProcureOrder';
@Form.create()
@connect(({
            sales,
            global,
            material,
            store, procure
          }) => ({...sales, ...material, ...global, ...procure, ...store}))
export default class ModalSelectPkgMaterialLot extends FormBase {
  constructor(props) {
    super(props);
    const {record = {}} = this.props;
    this.state = {...record};
  }

  /**
   * 界面新建时带入产品数量，用来和含量一起计算原料数量
   * useMaterials：可用的采购物料（不同的物料）
   * materialRecords：采购物料批次（单一物料），useMaterials切换时，materialRecords切换
   * materialRecords中按时间来计算占用
   * state中存储当前界面的数据，只有state中的无素为空时，才从props中取
   * @returns {JSX.Element}
   */

  componentDidMount() {
    this.props.dispatch({
      type: 'global/getModel',
      payload: {table}
    });

    // this.props.dispatch({
    //   type: 'material/findMany',
    //   payload: {}
    // });

    this.props.dispatch({
      type: 'procure/findUsedProcureMaterials',
      payload: {}
    });
    /**
     * 查找可用物料信息
     */
    const {selectMaterialCode, materialCount} = this.state;
    const {form} = this.props;

    selectMaterialCode && materialCount && this.props.dispatch({
      type: 'sales/findUsedMaterialRecord',
      payload: {code: selectMaterialCode, materialCount}
    });
  }

  componentWillUnmount() {
    this.state = {};
  }

  renderFoot = () => {
    const {foot, value, modalRef, form, callback, record = {}} = this.props;
    if (foot) {
      return foot(value, modalRef);
    } else {
      return (
        <ModalFooter>
          <Button type="primary" onClick={() => {
            const {modalRef} = this.props;
            form.validateFields((err, values) => {
              if (err) {
                const {code} = err;
                const {errors} = code;
                errors.forEach(item => {
                  notification.error(item);
                });
                return;
              }
              const {usedMaterialRecord = [], isEdit = false} = this.props;
              const {usedProcureMaterialLots, selectMaterial, selectMaterialValue, count} = this.state;
              if (usedMaterialRecord.length === 0) {
                notify({type: "warn", message: "占用数量为0！"});
              }
              console.log('vvvv', values);
              _.merge(this.state, values);
              this.state.usedMaterialRecord = usedMaterialRecord;
              callback(this.state);
              modalRef.close();
            });
          }}>确定</Button>
          <Button onClick={() => {
            modalRef.close();
          }}>取消</Button>
        </ModalFooter>
      );
    }
  };

  getMaterialInfo() {

    return <div>

    </div>;
  }

  getMaterialOpt = (list) => {
    _.map(list, item => {
      const {name = " ", subcategory = " ", spec = " ", type = " ", number = " ", code} = item;

      item.value = name + " " + subcategory + " " + spec + " " + type + " " + number + " " + code;
    });
    return list.map(opt => (
      <Option key={opt.code}
              value={opt.value}
              label={'material'}>
        {/*{<Tooltip title={opt.code+opt.name+" "+opt.subcategory+" "+opt.spec}> {opt.name}</Tooltip>}*/}
        {opt.value}
      </Option>
    ));
  };

  onSearch = searchText => {
    const {materials = []} = this.props;

    if (!searchText || searchText === '') {
      this.state.materials = materials;
      const _temp = this.state;
      this.setState(_temp);
      return;
    }

    const temp = [];
    _.map(this.props.materials, item => {
      const {name} = item;
      if (name.includes(searchText)) {
        temp.push(item);
      }
    });
    const _temp = this.state;
    _temp.materials = temp;
    this.setState(_temp);
  };

  cols = [
    {
      title: "物料", dataIndex: 'code', key: 'code', render: (value, record) => {
        const {code, name} = record;
        return <MaterialElement code={code} name={name}></MaterialElement>;
      }
    },
    {
      title: "规格形态", dataIndex: 'code', key: 'code', render: (value, record) => {
        const {subcategory, spec} = record;
        return <MaterialElement subcategory={subcategory} spec={spec}></MaterialElement>;
      }
    },
    {
      title: "类型编号", dataIndex: 'code', key: 'code', render: (value, record) => {
        const {type, number} = record;
        return <MaterialElement type={type} number={number}></MaterialElement>;
      }
    },
    {
      title: "采购单编码", dataIndex: 'procureOrderCode', key: 'procureOrderCode', render: (value, record) => {
        const {vendor} = record;
        const data = [{key: '采购编码', value: value}, {key: '供应商', value: vendor}];
        return <ElementItem data={data}></ElementItem>;
      }
    },


    {
      title: "采购数量", dataIndex: 'count', key: 'count', render: (value, record) => {
        const {useCount = 0, inboundCount = 0} = record;
        const color = value - useCount > 0 ? '#22f' : '#f22';
        const data = [{key: '采购数量', value: value}, {
          key: '可用数量',
          value: <div style={{color}}>{value - useCount}</div>
        },
          {key: '入库数量', value: inboundCount}
        ];
        return <ElementItem data={data}></ElementItem>;
      }
    },
    {
      title: "占用数量", dataIndex: '_useCount', key: '_useCount'
      // render: (value, record) => {
      //   const {usedCount = 0} = record;
      //   return <a onClick={() => {
      //     ModalView.open(ModalEditUsedMaterialLotCount, {title: '修改占用数量', width: '920px'}, {
      //       usedCount: value,
      //       callback: data => {
      //         record.usedCount = data.usedCount;
      //         this.componentDidMount();
      //       }
      //     });
      //   }}>{usedCount}</a>;
      // }
    },
    {title: "去向", dataIndex: 'target', key: 'target'},
    {title: "单价", dataIndex: 'price', key: 'price'},
    {title: "采购单运费", dataIndex: 'shippingFee', key: 'shippingFee'},
    {
      title: "采购时间", dataIndex: 'createdTs', key: 'createdTs', render: value => {
        return <div>{moment(value).format('YYYY-MM-DD')}</div>;
      }
    },
    {
      title: "占用运费", dataIndex: 'shippingFee', key: 'shippingFee', render: (value, record) => {
        const {shippingFee = 0, _useCount = 0, count = 0} = record;
        const v = shippingFee * (_useCount / count);
        return <div>{v.toFixed(2)}</div>;
      }
    }

  ];

  render() {
    const {style, useMaterials = [], usedMaterialRecord = [], form, isEdit = false} = this.props;
    let {
      loading,
      selectMaterialCode,
      selectMaterialValue, materialCount
      // cost = 0,
      // procureShippingFee = 0
    } = this.state;

    let cost = 0, procureShippingFee = 0;
    // const {
    //   materialContent = this.state.materialContent
    // } = form.getFieldsValue();

    //   if (!isEdit) {
    _.map(usedMaterialRecord, item => {
      const {_useCount = 0, shippingFee = 0, count = 0, price = 0} = item;
      cost += _useCount * price;
      const v = shippingFee * (_useCount / count);
      procureShippingFee += v;
    });
    // cost = selectMaterialCode && materialContent ? cost : 0;
    // procureShippingFee = selectMaterialCode && materialContent ? procureShippingFee : 0;
    //   }

    return (
      <Form style={{...style}}>
        {
          <AutoCompletePlus style={{width: '200%', margin: '12px'}}
                            addonBefore="选择物料:"
                            dataSource={this.getMaterialOpt(useMaterials)}
                            allowClear
                            onSearch={this.onSearch}
                            defaultValue={selectMaterialValue}
                            onChange={value => {
                              //  form.setFieldsValue({store: undefined});
                            }}
                            onSelect={(value, option) => {
                              const {key} = option;
                              this.state[`selectMaterialCode`] = key;
                              this.state[`selectMaterialValue`] = value;
                              const temp = _.find(useMaterials, item => {
                                return item.code === key;
                              });
                              if (temp) {
                                _.merge(this.state, temp);
                              }
                              this.state.materialRecords = [];
                              this.props.dispatch({
                                type: 'sales/clearUsedMaterialRecord',
                                payload: {}
                              });
                              this.componentDidMount();
                            }}
          >
          </AutoCompletePlus>
          // </FormField> </FormLayout>
        }
        <ViewTitle title={'原料信息'}
          // actions={<Button type={'danger'} onClick={() => this.componentDidMount()}>占用采购原料</Button>}
        ></ViewTitle>
        <FormLayout form={form} cols={4} style={{marginTop: "24dx"}}>

          <FormField
            label={'原料用量'} required
            name={'materialCount'} initialValue={materialCount}>
            <InputNumber style={{width: '100%'}}
                         onChange={value => {
                           this.state.materialCount = value;
                           this.componentDidMount();
                         }}
            ></InputNumber>
          </FormField>
          <FormField
            label={'成本'}
            name={'cost'} initialValue={cost}
          >
            <InputNumber disabled style={{width: '100%'}}></InputNumber>
          </FormField>
          <FormField
            label={'采购运费成本'}
            name={'procureShippingFee'} initialValue={procureShippingFee}
          >
            <InputNumber disabled style={{width: '100%'}}></InputNumber>
          </FormField>
        </FormLayout>
        {
          <ViewTitle
            title={'采购原料清单'}
            //  subTitle={str}
            // actions={<Button>占用物料</Button>}
          ></ViewTitle>}

        {<Table
          className={styles.antTable}
          bordered={true}
          rowKey={record => record.pmLotId}
          columns={this.cols}
          dataSource={usedMaterialRecord}
          scroll={{x: true}}
          //   rowSelection={rowSelection}
          loading={loading}
          // onRow={(record) => ({
          //   onClick: () => onSelectRow(record)
          // })}
          pagination={{
            current: this.state.current,
            total: this.state.total,
            showSizeChanger: true,
            onChange: page => {
              this.state.current = page;
              this.componentDidMount();
            },
            onShowSizeChange: (current, pageSize) => {
              this.state.current = 1;
              this.state.pageSize = pageSize;
              this.componentDidMount();
            }
          }}
        ></Table>}

        {this.renderFoot()}
      </Form>
    );
  }
}

